package org.wlgzs.office_exam_student.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author song(mejeesong@qq.com) 2018年1月24日 所有Dao类需要继承此类以获得操作数据库能力
 */
public class BaseDao<T> {
	
	public static final int BEAN_HANDLER = 1;
	public static final int BEAN_LIST_HANDLER = 2;
	
	@FunctionalInterface
	public interface SqlTask<T> {
		T exec(MyQueryRunner qr);
	}
	
	private Class<T> entityClass = null;

	private static final DataSourceProvider dsp = new C3p0DataSourceProvider();
	protected Logger logger = null;

	@SuppressWarnings("unchecked")
	public BaseDao() {
		this.logger = LoggerFactory.getLogger(this.getClass());
		Type type = this.getClass().getGenericSuperclass();
		if (!(type instanceof ParameterizedType)) {
			type = type.getClass().getSuperclass().getGenericSuperclass();
		}
		entityClass = (Class<T>) ((ParameterizedType) type).getActualTypeArguments()[0];
	}

	public final DataSource getDataSource() {
		return dsp.getDataSource();
	}

	/**
	 * @author song(mejeesong@qq.com)
	 * @date 2018年1月24日
	 * @return 一个自动获得数据库连接的QueryRunner
	 *
	 */
	private final MyQueryRunner getQueryRunner() {
		QueryRunner qr = new QueryRunner(dsp.getDataSource());
		return new MyQueryRunner(qr,entityClass);
	}

	@SuppressWarnings("hiding")
	public final <T> T exec(SqlTask<T> task) {
		MyQueryRunner qr = getQueryRunner();
		long start = System.currentTimeMillis();
		T res = task.exec(qr);
		logger.debug("exec sqlTask {} millis:{}", (System.currentTimeMillis() - start), qr.toString());
		return res;
	}
	
	

	
	protected final HumpRowProcessor getHrp() {
		return new HumpRowProcessor(entityClass);
	}
	protected final HumpRowProcessor getBh() {
		
		return new HumpRowProcessor(entityClass);
	}
	protected final HumpRowProcessor getBlh() {
		return new HumpRowProcessor(entityClass);
	}
	
}
